package objects 
{
	import flash.geom.Point;
	import mx.core.ButtonAsset;
	import objects.cicleItem.cicleItemTower;
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.events.Event;
	import objects.BulletManager;
	import starling.display.MovieClip;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.filters.BlurFilter;
	import com.greensock.*; 
	import com.greensock.easing.*;
	import starling.textures.Texture;
	/**
	 * ...
	 * @author Tuan
	 */
	
	public class Tower extends MyObject
	{	
		public var m_database:database;
		public var m_Sprite : Sprite ; //layer
		public var m_bulletManager : BulletManager ; 
		public var m_circleCollision : Image;
		public var m_cicleItem:cicleItemTower;
		public var m_testChoose:Boolean;
		public var m_range:Number; //get from database - su dung de range cua eclipse collsion
		public var m_percentDeso:Number; //get from database - su dung lam giam ty le anh huong cua armor dich 
		public var m_percentDouble:Number // get from database - ty le nay luc dau = 0, khi nang cap skill se tang len, su dung de lam double damage
		public var m_scaleUp:Number;
		public var m_cointTotal:Number;
		public var m_cooldownShoot : Number;
		public var m_archerSprite : MovieClip;
		public var m_scaleArcher : Number;
		public var m_attackState: int;
		public function Tower(_sprite : Sprite, _pos:Point,_coint:int)
		{
			m_range = 1;
			m_level = 1;
			
			m_Sprite = _sprite;
			m_cicleItem = new cicleItemTower(_sprite, _pos);
			m_pos = _pos;
			this.addEventListener(Event.ADDED_TO_STAGE, init);
			_sprite.addEventListener(TouchEvent.TOUCH, onTouch);
			_sprite.addChild(this);
			setInfoFromCoint(_coint);
			m_cointTotal = _coint;
		}
		private function onTouch(e:TouchEvent):void 
		{
			if (database.instance.m_testTouch == true)
			{
			var touch:Touch = e.getTouch(stage);
			if(touch)
			{
				var _pointTouch:Point = new Point(touch.globalX, touch.globalY);
				
				if(touch.phase == TouchPhase.BEGAN)
				{
					if (m_spriteMovie.bounds.containsPoint(_pointTouch) == true)
					{
						m_cicleItem.showCoint(m_cointTotal);
						m_cicleItem.clockAndUnclock();
						m_cicleItem.showCoint(m_cointTotal);
						if (m_testChoose == false)
						{
							m_testChoose = true;
							m_Sprite.setChildIndex(this, m_Sprite.numChildren);
							m_Sprite.setChildIndex(m_cicleItem, m_Sprite.numChildren);
						}
						else
						{
							m_testChoose = false;
						}
					}
					else
					{
						m_cicleItem.returnResult(_pointTouch);
						m_testChoose = false;
						if (m_cicleItem.m_result == -1)
						{
							m_testChoose = true;
						}
					}
				}
 
				else if(touch.phase == TouchPhase.ENDED)
				{
 
				}
 
				else if(touch.phase == TouchPhase.HOVER)
				{
					if (m_spriteMovie.bounds.containsPoint(_pointTouch) == true)
					{
						m_spriteMovie.filter= BlurFilter.createDropShadow(0,0,0xff0000,1,1,0.5);
						 
					}
					else
					{
						m_spriteMovie.filter= null;
					}
					
					m_cicleItem.blurFilter(_pointTouch);
				}
			}
			}
		}
		private function init(event:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, init);
			
		   m_animationState = Global.ARCHER_STAND;
		   m_attackState = Global.ARCHER_FRONT;
		   m_circleCollision = new Image (Assets.getTexture ("circle1"));
		   m_circleCollision.pivotX = m_circleCollision.width / 2 ;
		   m_circleCollision.pivotY = m_circleCollision.height / 2 ;
		   
		   m_circleCollision.x = m_pos.x;
		   m_circleCollision.y = m_pos.y;
		   
		   m_circleCollision.alpha = 0.3;

		   
		   //m_circleCollision.visible = false;
		   
		   this.addChild (m_circleCollision);
		   
		    m_scaleUp =Number(database.instance.RESULDTOWERARRAY[5]);//get from db
			m_percentDouble = Number(database.instance.RESULDTOWERARRAY[3]);
			m_percentDeso = Number (database.instance.RESULDTOWERARRAY[0]);
			m_circleCollision.scaleX = m_range* m_scaleUp;
			m_circleCollision.scaleY = m_range * m_scaleUp;
			    

		   m_choosedEnemy = null;
		  
		   m_spriteMovie = new MovieClip(Assets.getSpriteSheet().getTextures("archer_lv_1"), 1);
		   this.setAnchorPoint();
		   this.setPos(m_pos);
		   this.setScale(0.5);
		   this.addChild(m_spriteMovie);
		   
		   m_scaleArcher = 0.4;
		   m_archerSprite = new MovieClip(Assets.getSpriteSheet().getTextures("archer_stand_front"), 1);
		   m_archerSprite.pivotX = m_archerSprite.width / 2;
		   m_archerSprite.pivotY = m_archerSprite.height / 2;
		   m_archerSprite.scaleX = m_scaleArcher;
		   m_archerSprite.scaleY = m_scaleArcher;
		   m_archerSprite.x = m_pos.x;
		   m_archerSprite.y = m_pos.y - 30;
		   
		   this.addChild(m_archerSprite);
		   //time cooldown to shoot
		   m_coolDown = 1;
		   m_cooldownShoot = 1;
		   //speed's bullet from this tower
		   m_maxVelocity = 3.5;
		   
		   m_damage = 5; //get from database 
		   
		   m_collision = false;
		   m_bulletManager = new BulletManager();
		   
		}
		public function setInfoFromCoint(_coint:int):void
		{	
			m_cicleItem.setCicleInfo();
			m_cicleItem.showCoint(_coint);
		}
		public function shoot ( enemy : MyObject, dt : Number) : void {
			
			var totarget : Point = ccpSub(enemy.m_pos, new Point (m_pos.x, m_archerSprite.y )); 
			var a : Number = ccpDot(enemy.m_velocity, enemy.m_velocity) - ( m_maxVelocity * m_maxVelocity);
			var b : Number =  2 * ccpDot(enemy.m_velocity, totarget);
			var c : Number =  ccpDot (totarget, totarget);
			
			var p : Number =  - b / (2 * a);
			var q : Number =  Math.sqrt ( (b * b) - 4 * a * c ) / (2 * a);
			
			var t1: Number = p - q ;
			var t2: Number = p + q;
			var t : Number;
			if ( t1 > t2 && t2 > 0)
			{
				t = t2;
			}
			else 
			{
				t = t1;
			}
			var aimSpot : Point =  ccpAdd( enemy.m_pos, ccpMult (enemy.m_velocity, t));
			var bulletPath : Point = ccpSub (aimSpot, m_pos);
			var timeToImpact : Number =  bulletPath.length / m_maxVelocity / 60;
			
			m_bulletManager.addBullet ( new Bullet (this, new Point (m_pos.x, m_archerSprite.y ), timeToImpact, m_maxVelocity,m_damage, m_level, m_percentDeso, m_percentDouble)); 
			database.instance.m_Sound.playSound("Sound_Arrow");
			
			for ( var i : int = 0; i < m_bulletManager.getListBullet().length ; i++)
			{
			    m_bulletManager.getBullet(i).setTarget ( aimSpot, enemy);
				m_bulletManager.getBullet(i).m_Active = true;
			}
		}
		
		override public function update(dt:Number):void
		{
			m_cicleItem.m_level = m_level;
			m_cicleItem.m_damage = m_damage;
			m_cicleItem.update(dt);
			
			//set archer
			if (m_animationState == Global.ARCHER_STAND && m_choosedEnemy!=null)
			{
				m_animationState = Global.ARCHER_ATTACK;
			}
		    if (m_choosedEnemy != null &&  m_choosedEnemy.m_pos.y <= m_pos.y && m_animationState == Global.ARCHER_ATTACK) // XOAY back 
			{
				m_attackState = Global.ARCHER_BACK;
				swapFrame (m_archerSprite, Assets.getSpriteSheet().getTexture("archer_attack_back"));
			}
			else if (m_choosedEnemy != null &&  m_choosedEnemy.m_pos.y > m_pos.y && m_animationState == Global.ARCHER_ATTACK) // XOAY  front
			{
				m_attackState = Global.ARCHER_FRONT;
				swapFrame (m_archerSprite, Assets.getSpriteSheet().getTexture("archer_attack_front"));
			}
			if (m_choosedEnemy != null && m_choosedEnemy.m_pos.x < m_pos.x ) // xoay X thang archer
			{
				if (m_attackState == Global.ARCHER_BACK)
				{
				 m_archerSprite.scaleX =  m_scaleArcher;
				}
				else if (m_attackState == Global.ARCHER_FRONT)
				{
					m_archerSprite.scaleX = - m_scaleArcher;
				}
			}
			
			else if ( m_choosedEnemy != null && m_choosedEnemy.m_pos.x >= m_pos.x  )
			{
				if (m_attackState == Global.ARCHER_BACK)
				{
				   m_archerSprite.scaleX = - m_scaleArcher;
				}
				else if (m_attackState == Global.ARCHER_FRONT)
				{
					m_archerSprite.scaleX =  m_scaleArcher;
				}
			}
			
			
			
			
			if (m_choosedEnemy== null && m_animationState == Global.ARCHER_ATTACK) 
			{
				m_animationState = Global.ARCHER_STAND;
				swapFrame (m_archerSprite, Assets.getSpriteSheet().getTexture("archer_stand_front"));
			}
			
			
			//end set archer
			if (m_testChoose == true)
			{
				if (m_cicleItem.m_spriteMovie.alpha < 1)
				{
					m_circleCollision.alpha =0.3;
				}
				m_cicleItem.alphaUp();
			}
			else
			{
				m_cicleItem.alphaDown();
				m_circleCollision.alpha = 0;
			}
		  m_bulletManager.update(dt);
		  
		  if( m_choosedEnemy !=null && m_choosedEnemy.m_hp <=0 ) // quai' het' mau thi huy
	      {     
		       m_choosedEnemy = null;
		       m_collision = false;
	      }
		  
		  if(m_choosedEnemy!=null && m_collision  == true ) // check and shoottttttt
	      {
		     m_coolDown += dt;
		     
		    if(m_coolDown >=m_cooldownShoot)
		    {
			  m_coolDown = 0;
			  shoot(m_choosedEnemy,dt);
		    }
          }
		  if(m_choosedEnemy!=null && m_collision  == true) //ra khoi area thi release enemy
	      {
		    if(m_circleCollision.bounds.intersects (m_choosedEnemy.getRect()) == false)
	        {				
				  m_choosedEnemy = null;
				  m_collision = false;
	        }
          }
		  
		  if(m_bulletManager.getListBullet().length > 0) 
	      {
		      m_bulletManager.Collision( m_choosedEnemy, dt);
	      }
		
	
		}
		public function swapFrame(clip:MovieClip, texture :Texture):void 
		{
	       clip.addFrame(texture);
		   clip.removeFrameAt(0);
		   clip.currentFrame = 0;
		}
		public function levelUpAndSale(dt:Number, _coint:int):int
		{
			if (m_cicleItem.m_result == 1)
			{
				if ( m_cicleItem.m_baseItem[0].m_coint <= _coint)
				{
					//nang cap cac thong so
					this.m_damage += 5;
					m_level += 1;
					if (m_level == 2)
					{
						m_cooldownShoot = 0.85;
					}
					else if (m_level == 3)
					{
						m_cooldownShoot = 0.75;
					}
					
					m_scaleUp += 0.2;
				    m_circleCollision.scaleX = m_range* m_scaleUp;
		            m_circleCollision.scaleY = m_range* m_scaleUp;
					//cap nhat cac thong so
					_coint -= m_cicleItem.m_baseItem[0].m_coint;
					m_cicleItem.m_level = m_level;
					setInfoFromCoint(_coint);
					
					//tao lai hinh anh
					//m_spriteMovie = new MovieClip(Assets.getAtlas().getTextures("canon_" + m_level + "_"), 1);
					swapFrame (m_spriteMovie, Assets.getSpriteSheet().getTexture("archer_lv_" + m_level));
					//this.setAnchorPoint();
					if (m_level == 2)
					{
				        m_spriteMovie.scaleX = 0.6;
					}
					if (m_level == 3)
					{
						//m_archerSprite.y -= 5;
						m_spriteMovie.scaleY = 0.6;
				        m_spriteMovie.scaleX = 0.9;
						
					}
					
					//this.setPos(m_pos);
					


					//ket thuc
					m_cicleItem.m_result = 0;
					
					//tra ve coint
					return _coint;
				}
			}
			if (m_cicleItem.m_result == 2)
			{
				return _coint -= m_cicleItem.m_baseItem[1].m_coint;
			}
			return _coint;
		}
		public function updateCoint(dt:Number,coint:int):int
		{
			m_cicleItem.showCoint(coint);
			if (m_cicleItem.m_result == 1&&m_cicleItem.m_baseItem[0].m_coint<=coint)
			{
			   m_scaleUp += 0.2;
			   m_circleCollision.scaleX = m_range* m_scaleUp;
		       m_circleCollision.scaleY = m_range* m_scaleUp;
			   m_cicleItem.m_testSetInfo = false;
			   m_level += 1;
			   m_spriteMovie = new MovieClip(Assets.getAtlas().getTextures("canon_" + m_level + "_"), 1);
			   this.setAnchorPoint();
			   this.setPos(m_pos);

			   
			   m_cicleItem.m_result = 0;
			   coint -= m_cicleItem.m_baseItem[0].m_coint;
			   return coint;
		  }
		  if (m_cicleItem.m_result == 2)
		  {
			  return coint -= m_cicleItem.m_baseItem[1].m_coint;
		  }
		  return coint;
		}
		override public function Collision ( _enemy : MyObject, dt : Number) :void
		{
			//if ( m_circleCollision.bounds.intersects (_enemy.getRect()) == true)
			//{
				if (this.TestCollisionelip_Point (_enemy.m_pos, m_circleCollision)==true)
				{
					if (m_choosedEnemy == null && m_collision == false)
					{
						m_choosedEnemy = _enemy;
						m_collision = true;
					}
				}
			//}
		}

		public function swapFrames(clip:MovieClip, textures:Vector.<Texture>):void 
		{
 
	      // remove all frame but one, since a MovieClip is not allowed to have 0 frames
		  
		  

          	while(clip.numFrames > 1){
		    clip.removeFrameAt(0);
	        }
 
	         // add new frames
	          for each (var texture:Texture in textures){
		       clip.addFrame(texture);
	          }
 
	        // remove that last previous frame
           	clip.removeFrameAt(0);
 
	         // set to frame 1
	        clip.currentFrame = 1;
		 }
		  
		public function setAnchorPoint():void {
			m_spriteMovie.pivotX = m_spriteMovie.width / 2 ;
			m_spriteMovie.pivotY = m_spriteMovie.height / 2 ;
		}
		public function setPos ( _pos : Point) : void
		{
			m_spriteMovie.x = _pos.x;
			m_spriteMovie.y = _pos.y;
		}
		public function setScale ( _scale : Number) :void
		{
			m_spriteMovie.scaleX = _scale;
			m_spriteMovie.scaleY = _scale ;
		}
		override public function release():void {
			
			m_cicleItem.removeChildren();
			m_cicleItem.release();
			removeChildren();	
		}
	
		
	}

}
